<template>
  <div class="tree-container">
    <div class="left-tree" :style="{width: left + 'px'}">
      <div class="trigger" @mousedown="dragLine">
        <img src="../../../assets/img/trigger.png" alt="trigger">
      </div>

      <div class="filter-container">
        <div class="tree-header">
          <span class="page-title">组织架构树配置</span>
          <div class="btn-list">
            <!--              <p class="btn-item" @click="handleCreate({level: -1})">-->
            <!--                <i class="el-icon-plus" />-->
            <!--              </p>-->
            <p class="btn-item" @click="handleReset">
              <i class="el-icon-refresh-left"/>
            </p>
            <!--              <p class="btn-item" @click="handleMultiDelete">-->
            <!--                <i class="el-icon-delete" />-->
            <!--              </p>-->
          </div>
        </div>
        <div class="tree-list">
          <!--            show-checkbox-->
          <el-tree
            :props="treeProps"
            :data="treeData"
            node-key="id"
            :expand-on-click-node="false"
            @node-click="handleNodeClick">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span class="label ellipsis__more" :title="data.departmentName">
                    {{ data.departmentName }}
                  </span>
                  <span class="tree-option">
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-circle-plus-outline"
                      @click="() => handleCreate(data)">
                    </el-button>
                    <!--                     <el-button-->
                    <!--                       type="text"-->
                    <!--                       size="mini"-->
                    <!--                       icon="el-icon-edit"-->
                    <!--                       v-if="data.level !== 0"-->
                    <!--                       @click="() => handleEditRow(data)">-->
                    <!--                    </el-button>-->
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-delete"
                      style="color: red"
                      v-if="data.level !== 0"
                      @click="() => handleDelete(data)">
                    </el-button>
                  </span>
                </span>
          </el-tree>
        </div>
      </div>
    </div>
    <div class="right-container" style="padding: 10px" :style="{width: right}">
      <page-header-tool :title="title" :btns="modBtns" :max="4"></page-header-tool>
      <div>
        <el-form
          ref="form"
          class="kc-detail-form"
          label-position="right"
          label-width="120px"
          :model="form"
        >
          <el-form-item label="部门代码" prop="departmentCode">
            <el-input v-model="form.departmentCode" :disabled="true"/>
          </el-form-item>
          <el-form-item label="部门名称" prop="departmentName">
            <el-input v-model="form.departmentName" :disabled="true"/>
          </el-form-item>
          <el-form-item label="负责人" prop="leader">
            <el-input v-model="form.leader" :disabled="true"/>
          </el-form-item>
          <el-form-item label="状态" prop="state" placeholder=" ">
            <el-select style="width: 100%" v-model="form.state" :disabled="true">
              <el-option
                v-for="item in banStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="父节点" prop="frontOrganStructure">
            <el-input v-model="form.frontOrganStructure" :disabled="true"/>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <modify-detail ref="modifyDialog" @ok="getTree"/>
  </div>
</template>

<script>
import {tableOption} from './const/options';
import {tableBaseMixin} from "@/mixins/tableBase";
import {BaseData} from "./const/data"
export default {
  name: 'ledger',
  mixins: [tableBaseMixin],
  data() {
    return {
      left: 300,
      leftPos: 300,
      startX: 0,
      moving: false,
      right: '100%',

      banStatus:[],
      treeProps: {
        children: 'child',
        label: 'departmentName'
      },
      modBtns: [],
      treeData: [],
      tableOption,

      selectionData: [],
      tableData: [],
      listLoading: false,
      tableBtns: [
        {
          name: '编辑',
          click: this.handleEditRow
        },
        {
          name: '删除',
          click: this.handleDelete,
          color: 'red'
        },
        {
          name: "启用",
          click: this.handleEnable,
          show: (row, index) => {
            return row.status === '0';
          },
        },
        {
          name: "停用",
          click: this.handleStop,
          color: '#E6A23C',
          show: (row, index) => {
            return row.status === '1';
          },
        },
      ],
      title: '部门详情',

      form: {
        departmentCode: '',
        departmentName: '',
        frontOrganStructure: '',
        baseId: '',
        leader: '',
        mesSchedulManagementId: '',
        organNcCode: '',
        state: ' ',
        schedulFlag: ''
      },
    };
  },
  computed: {},
  created() {
    this.init();
  },
  methods: {
    init() {
      this.page.currentPage = 1;
      this.getTree();
      // this.getList()
    },
    getTree() {
      this.treeData=BaseData
    },

    handleNodeClick(data) {
      if (data.level !== 0) {
        this.form = data
      }
    },
    handleReset() {
      this.getTree()
    },
    /* C 新增主数据 */
    handleCreate(row) {
      this.$refs.modifyDialog.add(row, this.treeData)
    },
    /* U 编辑主数据 */
    handleEditRow(row, index) {
      this.$refs.modifyDialog.edit(row)
    },

    /* 删除数据 */
    handleDelete(row) {
      this.$confirm('是否确认删除该信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRequest(row)
      })
    },
    // 删除仓库
    async deleteRequest(row) {
     
    },


    // 启用
    handleEnable(row) {
      this.$confirm('是否确认启用', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.EnableRequest(row.id)
      })
    },
    // 批量启用
    handleMultiEnable() {
      if (this.selectionData.length === 0) {
        return this.$message.error('请选择要操作内容')
      }
      this.$confirm('是否确认启用', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = []
        try {
          ids = this.selectionData.map(i => {
            if (i.status === '1') {
              throw {code: i.code, err: 1}
            }
            return i.id
          })
        } catch (e) {
          if (e.err === 1) {
            return this.$message.error(`库位编码：${e.code}, 非停用状态，无法启用！`)
          }
        }
        this.EnableRequest(ids.join(','))
      })
    },
    async EnableRequest(ids) {
      try {
        this.listLoading = true;
        const response = await enableByIds(ids)
        const {code, msg} = response.data
        if (code === 0) {
          this.$message({
            showClose: true,
            message: '启用成功',
            type: 'success'
          });
          this.searchChange();
        } else {
          this.$message.error(msg)
        }
      } finally {
        this.listLoading = false
      }
    },
    // 停用
    handleStop(row) {
      this.$confirm('是否确认停用', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.stopRequest(row.id)
      })
    },
    // 批量停用
    handleMultiStop() {
      if (this.selectionData.length === 0) {
        return this.$message.error('请选择要操作内容')
      }
      this.$confirm('是否确认停用', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = []
        try {
          ids = this.selectionData.map(i => {
            if (i.status === '0') {
              throw {code: i.code, err: 1}
            }
            return i.id
          })
        } catch (e) {
          if (e.err === 1) {
            return this.$message.error(`库位编码：${e.code}, 非启用状态，无法停用！`)
          }
        }
        this.stopRequest(ids.join(','))
      })
    },
    async stopRequest(ids) {
      try {
        this.listLoading = true;
        const response = await stopByIds(ids)
        const {code, msg} = response.data
        if (code === 0) {
          this.$message({
            showClose: true,
            message: '停用成功',
            type: 'success'
          });
          this.searchChange();
        } else {
          this.$message.error(msg)
        }
      } finally {
        this.listLoading = false
      }
    },
    dragLine(e) {
      // console.log(e);
      this.startX = e.clientX;
      document.addEventListener("mousemove", this.dragMove);
      document.addEventListener("mouseup", this.dragEnd);
    },
    dragMove(event) {
      // console.log(event);
      // console.log(startX);
      this.moving = true;
      const distanceX = event.clientX - this.startX;
      let left = this.leftPos + distanceX;
      // this.left += distanceX;
      if (left < 300) {
        left = 300;
      }
      this.left = left;
      this.right = document.body.clientWidth - left + 'px'
    },
    dragEnd() {
      this.leftPos = this.left;
      this.moving = false;
      document.removeEventListener("mousemove", this.dragMove);
      document.removeEventListener("mouseup", this.dragEnd);
    },
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.tree-container {
  display: flex;
  padding: 0 10px;
  width: 100%;
  height: 100%;

  .left-tree {
    margin-right: 15px;
    width: 20%;
    position: relative;

    .trigger {
      cursor: pointer;
      position: absolute;
      right: -6px;
      top: 45%;
      border-radius: 20px;
      padding: 12px 4px;
      background-color: #898989;
      text-align: center;

      img {
        width: 6px;
      }

      &:hover {
        background-color: $themeColor;
      }
    }

    .filter-container {
      height: 100%;
      background-color: #ffffff;
      padding: 10px;

      .tree-header {
        height: 24px;
        line-height: 24px;
        font-size: 16px;
        font-weight: bold;
        display: flex;
        justify-content: space-between;
        width: 100%;
        margin-bottom: 20px;

        .btn-list {
          display: flex;
          justify-content: space-between;

          .btn-item {
            margin: 0 8px 0 0;
            cursor: pointer;
          }
        }
      }
    }

    .custom-tree-node {
      //display: flex;
      //justify-content: space-between;
      width: 100%;
      font-size: 12px;
      padding: 0 10px;

      .label {
        line-height: 28px;
        flex-basis: 170px;
        overflow: hidden;
        display: inline-block;
        width: 74%;
      }

      .ellipsis__more {
        overflow: hidden; //超出的文本隐藏
        text-overflow: ellipsis; //溢出用省略号显示
        white-space: nowrap; //溢出不换行
      }

      .tree-option {
        float: right;
      }
    }
  }

  .right-container {
    width: 80%;
    height: 100%;
    background-color: #ffffff;
  }
}

.tree-list {
  overflow-y: scroll;
  height: 80vh;
}
</style>
